import DamageArea from "../entity/DamageArea";
import Enemy from "../entity/Enemy";
import Player from "../entity/Player";
import RoomType from "../entity/RoomType";
import { Config } from "../utils/config";
import { Emitter } from "../utils/emmiter";
import { MessageType } from "../utils/message";
import { Utils } from "../utils/utils";
import DD from "./dynamic_data_manager";
import JsonManager from "./json_manager";
import PoolManager from "./pool_manager";
import ResourceManager from "./resources_manager";
import StorageManager from "./storage_manager";
import UIManager from "./ui_manager";

const { ccclass, property } = cc._decorator;

//整个游戏的控制器
declare global {
    interface Window {
        winSize: any
    }
}
@ccclass
export default class MainManager extends cc.Component {
    static instance: MainManager = null

    spawnPoint: cc.Node = null;
    heroPrefab: cc.Prefab = null;
    enemies: Enemy[] = []
    timer: number = 0
    spawnInterval = 2
    globalId: number = 1;
    curIds: number[] = []
    genDone: boolean = false
    isEndGame: boolean = false;
    damageArea: DamageArea = null;
    player: Player = null
    genObjContaier: cc.Node
    baesIds: any[] = [

        [1, 1, 1],
        [1, 1, 1, 2, 2, 2],
        [1, 1, 1, 1, 2, 2, 2, 3, 3],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 1],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 3],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 3],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 5],
        [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
        [3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
    ]
    ids: any[] = []
    index: number = 0
    curWave: number = 0
    private totalLevels: number = 15; // 总关卡数
    private currentLevel: number = 1; // 当前关卡

    onLoad() {
        MainManager.instance = this
        this.setDesignResolution()
        ResourceManager.instance.init()
        this.spawnPoint = cc.find('Canvas/spawn')
    }

    resLoaded() {
        console.log('资源加载完毕')

        //判断是否初次开始游戏
        let configData = StorageManager.instance.loadDataByKey('config')
        if (configData) {
            //加载配置 判断版本号

            return
        }
        this.player = cc.find('Canvas/hero_1').getComponent(Player)
        this.damageArea = cc.find("Canvas/damage").getComponent(DamageArea)
        this.genObjContaier = cc.find('Canvas/genObjContaier')
        // if (StorageManager.instance.loadDataByKey('userdata')) {
        StorageManager.instance.loadPlayerData()
        // }
        this.generateLevel(10)
        cc.director.getCollisionManager().enabled = true;
        cc.director.getPhysicsManager().enabled = true;
        DD.instance.config = { audio: 100, version: '1.0', music: 100 }
        StorageManager.instance.playerData.maxHp = 2000;
        StorageManager.instance.playerData.maxHp += DD.instance.caculateHpEtraRate()
        StorageManager.instance.playerData.hp = StorageManager.instance.playerData.maxHp;
        cc.director.getScheduler().setTimeScale(8);
        UIManager.instance.findUI();
        // Emitter.fire(MessageType.playerLevelUp)

        Emitter.register(MessageType.gameStart, (name, data) => {
            let type = DD.instance.rooms[StorageManager.instance.levelInfo.curLevel-1]
            if(type == RoomType.Shop){
                UIManager.instance.showTip('随机获得装备了')
                StorageManager.instance.levelInfo.maxLevel++;
                let equips =   JsonManager.instance.getDataByName("equip")
                let ids = Object.keys(equips)
                cc.log('equpIds')
                cc.log(ids)
                StorageManager.instance.playerData.equipIds.add(ids[Utils.getRandomNumInRange(0,ids.length-1)])
                
                Emitter.fire(MessageType.levelIncrease)
            }else if(type == RoomType.Bonfire){
                UIManager.instance.showTip('玩家升级成功')
                StorageManager.instance.levelInfo.maxLevel++;
                Emitter.fire(MessageType.levelIncrease)
            } else{
                this.genDone = false;
                this.setLevelIds()
                this.curIds = this.ids[this.curWave]
                MainManager.instance.isEndGame = false;
                this.resetAllInfo()
                cc.director.resume()
                this.genCurWaveEnemy()
                this.unschedule(this.genWavesEnemy)
                this.schedule(this.genWavesEnemy, 20)
            }
            
        }, '')
        // Emitter.fire(MessageType.returnToLevelList)


    }

    // 生成关卡
    generateLevel(level: number) {
        const roomCount = 5 + level; // 每关房间数量逐渐增加
        const rooms: RoomType[] = [];

        // 默认最后一个房间是Boss房间，倒数第二个是篝火房间
        rooms[roomCount - 1] = RoomType.Boss;
        rooms[roomCount - 2] = RoomType.Bonfire;

        // 随机生成商店和精英房间
        const shopCount = Math.floor(Math.random() * 2) + 1; // 1-2个商店
        const eliteCount = Math.floor(Math.random() * 2) + 1; // 1-2个精英房间

        for (let i = 0; i < shopCount; i++) {
            const index = Math.floor(Math.random() * (roomCount - 2)); // 不在最后两个房间生成
            rooms[index] = RoomType.Shop;
        }

        for (let i = 0; i < eliteCount; i++) {
            const index = Math.floor(Math.random() * (roomCount - 2)); // 不在最后两个房间生成
            rooms[index] = RoomType.Elite;
        }

        // 填充剩余房间为普通房间
        for (let i = 0; i < roomCount; i++) {
            if (!rooms[i]) {
                rooms[i] = RoomType.Normal;
            }
        }
        cc.log(rooms)
        DD.instance.rooms = rooms
        // 生成房间节点
        // this.createRooms(rooms);
    }

    // 创建房间节点
    // createRooms(rooms: RoomType[]) {
    //     for (let i = 0; i < rooms.length; i++) {
    //         const roomNode = cc.instantiate(this.roomPrefab);
    //         roomNode.parent = this.node;
    //         roomNode.setPosition(i * 300, 0); // 水平排列房间

    //         const roomScript = roomNode.getComponent("Room");
    //         if (roomScript) {
    //             roomScript.init(rooms[i]);
    //         }
    //     }
    // }

    // 更新房间UI


    // 进入房间
    onEnterRoom() {
        switch (this.roomType) {
            case RoomType.Normal:
                this.spawnEnemies();
                break;
            case RoomType.Elite:
                this.spawnElite();
                break;
            case RoomType.Shop:
                this.openShop();
                break;
            case RoomType.Bonfire:
                this.restAtBonfire();
                break;
            case RoomType.Boss:
                this.fightBoss();
                break;
        }
    }

    // 生成小怪
    spawnEnemies() {
        cc.log("生成小怪");
    }

    // 生成精英怪
    spawnElite() {
        cc.log("生成精英怪");
    }

    // 打开商店
    openShop() {
        cc.log("打开商店");
    }

    // 篝火休息
    restAtBonfire() {
        cc.log("篝火休息，恢复生命值");
    }

    // 战斗Boss
    fightBoss() {
        cc.log("战斗Boss");
    }

    // 进入下一关
    nextLevel() {
        this.currentLevel++;
        if (this.currentLevel > this.totalLevels) {
            cc.log("游戏通关！");
            return;
        }
        this.node.removeAllChildren(); // 清空当前关卡
        this.generateLevel(this.currentLevel);
    }

    setLevelIds() {
        this.ids = this.baesIds
        if (StorageManager.instance.levelInfo.curLevel == 5 || StorageManager.instance.levelInfo.curLevel == 10) {
            this.ids[this.ids.length - 1].push(6)
        } else {
            this.ids[this.ids.length - 1].push(5)
        }
    }

    resetAllInfo() {
        StorageManager.instance.playerData.curExp = 0
        StorageManager.instance.playerData.level = 1
        StorageManager.instance.skills = []
        StorageManager.instance.playerData.curExp = 0
        StorageManager.instance.ballCount = 1
        this.clearAllEnemies()
        MainManager.instance.curWave = 0;
        MainManager.instance.index = 0;
        StorageManager.instance.playerData.hp = StorageManager.instance.playerData.maxHp
        cc.find('Canvas/hero_1').getComponent(Player).applySkillEffect()
        PoolManager.instance.removeObjByContainer(this.genObjContaier)
    }

    genWavesEnemy() {
        this.genDone = false;
        this.curWave++;
        if (this.curWave >= this.ids.length) {
            this.genDone = true;
            return;
        }
        // cc.log("------------------------------第" + this.curWave + "敌人生成------------------------------")
        Emitter.fire(MessageType.uiUpdate);
        this.genCurWaveEnemy()
    }

    genCurWaveEnemy() {
        this.curIds = this.ids[this.curWave] ? this.ids[this.curWave] : []

        this.spawnEnemy(1)
        // this.schedule(this.spawnEnemy, this.spawnInterval); // 定时生成敌人
    }

    getGlobalId() {
        this.globalId++;
        return this.globalId;
    }

    spawnEnemy(id: number) {

        if (this.genDone) {
            return
        }
        for (let i = 0; i < this.curIds.length; i++) {
            if (this.curIds[i]) {
                // 创建敌人实例
                let enemy = PoolManager.instance.createObjectByName('hero_2', this.spawnPoint.parent)
                // 随机设置敌人位置
                const screenWidth = cc.view.getVisibleSize().width - 50;
                const randomX = Math.random() * screenWidth - screenWidth / 2;
                let enemyScript: Enemy = enemy.getComponent(Enemy);
                enemyScript.globalId = this.getGlobalId();
                enemyScript.init(this.curIds[i])
                enemy.setPosition(randomX, this.spawnPoint.y)

                // 添加到敌人数组
                this.enemies.push(enemyScript);
            }
        }

        // this.index++
        // if (this.curWave >= this.ids.length-1) {
        //     this.genDone = true;
        //     return;
        // }
    }



    //适配
    setDesignResolution() {
        var canvas = cc.find("Canvas").getComponent(cc.Canvas)
        var winSize = cc.winSize
        window.winSize = winSize
        if (winSize.width / winSize.height > 640 / 1134) {
            canvas.fitWidth = false
            canvas.fitHeight = true
        } else {
            canvas.fitWidth = true
            canvas.fitHeight = false
        }
    }

    removeEnemyById(globalId) {
        // 查找敌人
        const index = this.enemies.findIndex(e => e.globalId === globalId);
        if (index !== -1) {

            const enemy = this.enemies[index];
            if (!this.isEndGame) {
                StorageManager.instance.addExp(enemy.exp);
                Emitter.fire(MessageType.uiUpdate);
            }
            enemy.node.destroy(); // 销毁敌人节点
            this.enemies.splice(index, 1); // 从数组中移除
            cc.log(this.enemies.length, this.genDone)
            if (this.enemies.length == 0 && this.genDone) {
                // this.curWave++;
                if (!this.isEndGame) {
                    this.isEndGame = true;

                    cc.director.pause()
                    StorageManager.instance.levelInfo.money += 500;
                    StorageManager.instance.levelInfo.maxLevel++;
                    let winTicket = DD.instance.roomType==RoomType.Elite?20:10
                    StorageManager.instance.remainSkillTicket+= winTicket
                    DD.instance.setWinItem()
                    Emitter.fire(MessageType.gameEnd)
                } else {
                    this.index = -3
                    this.genDone = false;

                }

            }
        }
    }

    clearAllEnemies() {
        // 销毁并清空所有敌人
        // this.enemies.forEach(enemy => enemy.node.destroy());
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            if (this.enemies[i]) {
                this.removeEnemyById(this.enemies[i].globalId)
            }

        }
        this.enemies = [];
    }


}
